﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DBEntity;

namespace iver.Controllers
{
    public class AuthController : ApiController
    {
        /// <summary>
        /// 登录参数
        /// </summary>
        public class reqLoginUser
        {
            /// <summary>
            /// 用户名
            /// </summary>
            public string userName { set; get; }
            /// <summary>
            /// 密码
            /// </summary>
            public string userPwd { set; get; }
            /// <summary>
            /// 验证码
            /// </summary>
            public string imgCode { set; get; }
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="req"></param>
        /// <returns>jsonstr</returns>
        [HttpPost]
        public ResResult Login([FromBody]reqLoginUser req)
        {
            //System.Threading.Thread.Sleep(3000);
            if (req.userName == "" || req.userPwd == "" || req.imgCode == "" || req.userName.Length > 15 || req.userPwd.Length > 15)
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "用户名密码格式不正确",
                };
            }
            if (System.Web.HttpContext.Current.Session["imgcode"] == null)
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "请填写验证码"
                };
            }
            if (System.Web.HttpContext.Current.Session["imgcode"].ToString().ToLower() != req.imgCode.ToLower())
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "验证码错误"
                };
            }
            iverDB db = new iverDB();
            sysUser user = db.sysUser.FirstOrDefault(p => p.userName == req.userName && p.pwd == req.userPwd);
            if (user == null)
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "用户名或密码错误"
                };
            }
            if (user.isEnable == false)
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "该用户已被禁用"
                };

            }
            List<DBEntity.sysModule> moduleList = Help.BaseModuleList(new Entity.AuthInfo() { userId = user.id, isSuperAdmin = user.fid == -1 });

            string userName = user.userName;
            int userId = user.id;
            string userType = user.userType.ToString();
            string trueName = user.trueName.ToString();


            Entity.AuthInfo authInfo = new Entity.AuthInfo
            {
                trueName = trueName,
                userId = userId,
                userName = userName,
                isSuperAdmin = user.fid == -1,
                createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                moduleList = moduleList,
                IP = Help.GetIPAddress(),
            };
            //生成token,SecureKey是配置的web.config中，用于加密token的key，打死也不能告诉别人
            byte[] key = System.Text.Encoding.Default.GetBytes(System.Configuration.ConfigurationManager.AppSettings["SecureKey"]);
            //采用HS256加密算法
            string token = JWT.JsonWebToken.Encode(authInfo, key, JWT.JwtHashAlgorithm.HS256);
            Help.Log(authInfo, "login");
            return new ResResult()
            {
                success = true,
                result = new
                {
                    currentAuthority = user.authority,
                    token,
                }
            };

        }

        /// <summary>
        /// 图片验证码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult imgcode([FromBody]ReqImgCode req)
        {
            //System.Threading.Thread.Sleep(3000);
            return Help.imgcode(req);
        }
        //[HttpPost]
        //public ResResult test([FromBody]ReqID<double> req)
        //{
        //    int rtime = Help.checkReqTime(15, 1, "abc");
        //    return new ResResult
        //    {
        //        success = rtime >= 0,
        //        result = rtime,
        //        //result = new Random().Next().ToString(),
        //    };
        //}
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult currentUser()
        {
            Entity.AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo, false))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            return new ResResult
            {
                success = true,
                result = new
                {
                    //authInfo.userId,
                    authInfo.userName,
                    authInfo.trueName,
                    //authInfo.createTime,
                    authInfo.moduleList,
                }
            };

        }
    }
}